/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * diagEditCategoria.java
 *
 * Created on 18/10/2011, 16:58:48
 */
package carreras.gui;

import carreras.Configuracion;
import carreras.entidades.CatCorredorAuto;
import carreras.entidades.Categoria;
import carreras.entidades.Categorias;
import carreras.entidades.CorredorAuto;
import carreras.entidades.ManagerTorneo;
import carreras.logger.CarrerasLogger;
import carreras.negocio.NegCategorias;
import carreras.negocio.NegInscripcion;
import java.sql.SQLException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author lisandro
 */
public class diagEditCategoria extends javax.swing.JDialog {

    private static final String TITLE = "Editar Categoria";
    private CorredorAuto corredor_auto_categoria;
    private CatCorredorAuto corredores_auto_categoria;
    private CatCorredorAuto corredores_auto_categoria_filtrados;
    
    private Categorias categorias;
    
    private static boolean editando = false;
    
    /** Creates new form diagEditCategoria */
    public diagEditCategoria(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        init_busqueda();
        init_tables();
        init();
        load_categorias();
        isEditando();
        setTitle(TITLE);
        setLocationRelativeTo(null);
    }
    
    private void init(){
        rbDNI.setSelected(true);
        try{
            corredores_auto_categoria = new NegInscripcion().getInscriptos(ManagerTorneo.getInstance().getTorneo());//new carreras.negocio.CorredorAutoCategoria().getAllCorredorAutoCategoria(ManagerTorneo.getInstance().getTorneo());
            corredores_auto_categoria_filtrados = corredores_auto_categoria;
            actualiza_tbl(corredores_auto_categoria_filtrados);
        }catch(SQLException ex){
            System.err.println("sqlex:"+ex.getMessage());
        }
    }
    
    private void init_busqueda(){
        buttonGroup1.add(rbDNI);
        buttonGroup1.add(rbApellido);
        txtBusqueda.setText("");
    }
    
    private void init_tables(){
        Object[] loading = new Object[]{"Sin Datos"};
        
        tblAutoCorredor.setModel(new DefaultTableModel());
        tblAutoCorredor.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tblAutoCorredor.setAutoCreateRowSorter(false);
        tblAutoCorredor.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
            @Override
            public void valueChanged(ListSelectionEvent event) {
                if (event.getValueIsAdjusting()) {
                    return;
                }
                corredor_auto_seleccionado();
                
            };
        });
    }
    
    private void actualiza_tbl(final CatCorredorAuto cor_au_cat){
        CarrerasLogger.debug(diagEditCategoria.class, "cor_auto.size() "+cor_au_cat.size());
        final DefaultTableModel tmodel = new NotEditableTableModel();
        if(cor_au_cat.isEmpty()){
            tmodel.setColumnIdentifiers(new Object[]{"Sin Datos"});
        }else{
            tmodel.setColumnIdentifiers(new Object[]{"Numero","DNI","Nombre","Apellido","Categoria"});
            for(CorredorAuto ca: cor_au_cat){
                tmodel.addRow(new Object[]{ca.getNumero_asignado(),ca.getCorredor().getDni(),ca.getCorredor().getNombre(),ca.getCorredor().getApellido(),ca.getCategoria().getDescripcion()});
            }
        }
        tblAutoCorredor.setModel(tmodel);
        
    }
    
    private void filtra_corredor_auto(){
        String txt = txtBusqueda.getText();
        if(rbDNI.isSelected()){
            actualiza_tbl(corredores_auto_categoria_filtrados.filtrarDNI(txt));
        }else if(rbApellido.isSelected()){
            actualiza_tbl(corredores_auto_categoria_filtrados.filtrarApellido(txt));
        }else{
            throw new IllegalArgumentException("Opcion Desconocida");
        }
    }
    
    private void corredor_auto_seleccionado(){
        
      
        load_categorias();
        int idx = tblAutoCorredor.getSelectedRow();
        if(idx<0)
            return;
        corredor_auto_categoria = corredores_auto_categoria_filtrados.get(idx);
        txtNumero.setText(String.valueOf(corredor_auto_categoria.getNumero_asignado()));
        cmbCategorias.setSelectedItem(corredor_auto_categoria.getCategoria());
        select_categoria_cmb();
        editando = true;
        isEditando();
        
    }
    
    private void select_categoria_cmb() {
        for (Categoria a : categorias) {
            if (a.getId() == corredor_auto_categoria.getCategoria().getId()) {
                categorias.remove(a);
                DefaultComboBoxModel model = new DefaultComboBoxModel();
                model.addElement(a);
                for (Categoria c : categorias) {
                    model.addElement(c);
                }

                cmbCategorias.setModel(model);
                break;
            }
            
        }
    }

    private void load_categorias(){
        try{
            DefaultComboBoxModel model = new DefaultComboBoxModel();
            categorias = new carreras.negocio.NegCategorias().getCategorias();

            model.addElement("<Seleccione una categoria>");
            for (Categoria c : categorias) {
                model.addElement(c);
            }

            cmbCategorias.setModel(model);
        } catch (SQLException ex) {
            System.err.println("sqlex: " + ex.getMessage());
        }
    }

    
    private void guardar(){
        try{
            Categoria categoria_new = (Categoria) cmbCategorias.getSelectedItem();
            //hace lo mismo dos veces... wtf??
//            corredores_auto_categoria.remove(corredor_auto_categoria);
            corredor_auto_categoria.setCategoria(categoria_new);
            new NegInscripcion().updateCategoriaInscripcion(corredor_auto_categoria, ManagerTorneo.getInstance().getTorneo());
//            corredores_auto_categoria.add(corredor_auto_categoria);
            corredores_auto_categoria_filtrados = corredores_auto_categoria;
            //antes de actualizar la tabla...
            
            actualiza_tbl(corredores_auto_categoria_filtrados);
            editando = false;
            isEditando();
            load_categorias();
        }catch(ClassCastException ex){
            System.out.println("categoria no seleccionada");
            javax.swing.JOptionPane.showMessageDialog(null, "Debe seleccionar una nueva categoria");
            cmbCategorias.grabFocus();
            load_categorias();
            return;
        }catch(SQLException ex){
            System.err.println("sqlex:"+ex.getMessage());
        }
    }
    
    private void isEditando(){
        if (editando){
            btnGuardar.setEnabled(editando);
            cmbCategorias.setEnabled(editando);
        }else{
            btnGuardar.setEnabled(editando);
            txtNumero.setText("");
            cmbCategorias.setEnabled(editando);
        }
    }
    private void cerrar(){
        this.dispose();
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblAutoCorredor = new javax.swing.JTable();
        txtBusqueda = new javax.swing.JTextField();
        rbDNI = new javax.swing.JRadioButton();
        rbApellido = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtNumero = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cmbCategorias = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Corredores"));

        tblAutoCorredor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblAutoCorredor.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblAutoCorredorMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblAutoCorredor);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        txtBusqueda.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBusquedaKeyReleased(evt);
            }
        });

        rbDNI.setText("DNI");
        rbDNI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbDNIActionPerformed(evt);
            }
        });

        rbApellido.setText("Apellido");
        rbApellido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbApellidoActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Editar Categoria"));

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        jLabel1.setText("Numero: ");

        txtNumero.setEditable(false);
        txtNumero.setEnabled(false);

        jLabel2.setText("Categoria: ");

        cmbCategorias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(96, 96, 96)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbCategorias, 0, 366, Short.MAX_VALUE)
                            .addComponent(txtNumero, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)))
                    .addComponent(btnGuardar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(cmbCategorias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addComponent(btnGuardar)
                .addContainerGap())
        );

        jButton2.setText("Cerrar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(230, 230, 230)
                            .addComponent(rbDNI)
                            .addGap(49, 49, 49)
                            .addComponent(rbApellido))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtBusqueda, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbApellido)
                    .addComponent(rbDNI))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void rbDNIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbDNIActionPerformed
        txtBusqueda.grabFocus();
}//GEN-LAST:event_rbDNIActionPerformed

private void rbApellidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbApellidoActionPerformed
        txtBusqueda.grabFocus();
}//GEN-LAST:event_rbApellidoActionPerformed

private void txtBusquedaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusquedaKeyReleased
    filtra_corredor_auto();
}//GEN-LAST:event_txtBusquedaKeyReleased

private void tblAutoCorredorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblAutoCorredorMouseClicked
//    if(evt.getClickCount()==2){
//            corredor_auto_seleccionado();
//        }else{
//        isEditando();
//    }
}//GEN-LAST:event_tblAutoCorredorMouseClicked

private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
    guardar();
}//GEN-LAST:event_btnGuardarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        cerrar();//o cerrar xD
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        Configuracion.init_conf(args);
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(diagEditCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(diagEditCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(diagEditCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(diagEditCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                diagEditCategoria dialog = new diagEditCategoria(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cmbCategorias;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbApellido;
    private javax.swing.JRadioButton rbDNI;
    private javax.swing.JTable tblAutoCorredor;
    private javax.swing.JTextField txtBusqueda;
    private javax.swing.JTextField txtNumero;
    // End of variables declaration//GEN-END:variables
}
